// https://nuxt.com/docs/api/configuration/nuxt-config
const { fileURLToPath } = require('url');
export default defineNuxtConfig({
    alias: {
        img: fileURLToPath(new URL('./assets/images', import.meta.url)),
        resource: fileURLToPath(new URL('./assets', import.meta.url)),
        svg: fileURLToPath(new URL('./assets/svg', import.meta.url)),
    },

    modules: [
        // '@vant/nuxt',
        '@pinia/nuxt',
        'nuxt-gtag',
        '@nuxtjs/i18n',
        '@nuxt/devtools',
        '@hypernym/nuxt-anime',
        'nuxt-swiper', // '@ant-design-vue/nuxt',
        // '@nuxtjs/tailwindcss'
        '@nuxt/image',
        '@nuxtjs/sitemap',
    ],

    // sitemap: {
    //     // manually chunk into multiple sitemaps
    //     sitemaps: {
    //         posts: {
    //             include: ['/en/**'],
    //             // example: give blog posts slightly higher priority (this is optional)
    //             defaults: { priority: 0.7 },
    //         },
    //         pages: {
    //             exclude: ['/en/**'],
    //         },
    //     },
    // },

    // i18n: {
    //     locales: ['en'],
    //     defaultLocale: 'en',
    //     strategy: 'no_prefix'
    // },

    app: {
        //   anime: {
        //     autoImport: false
        //   },
        pageTransition: { name: 'page', mode: 'out-in' },
        
        // iOS 16.0 兼容性
        buildAssetsDir: '_nuxt',
        head: {
            meta: [
                {
                    charset: 'utf-8',
                },
                {
                    name: 'viewport',
                    content:
                        'width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no',
                },
            ],
            // initial-scale=1.0, maximum-scale=1.0, user-scalable=no,
            link: [
                {
                    href: '/images/favicon.ico',
                    rel: 'shortcut icon',
                },
                // {
                //     href: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css',
                //     rel: 'stylesheet',
                // },
                // {
                //     href: 'https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css',
                //     rel: 'stylesheet',
                // },
            ],
            script: [
                // 因为引入flexible会自动计算html的值
                // Flexible.js
                // {
                //     children: `!function(e,t){function n(){t.body?t.body.style.fontSize=12*o+"px":t.addEventListener("DOMContentLoaded",n)}function d(){var e=i.clientWidth/10;i.style.fontSize=e+"px"}var i=t.documentElement,o=e.devicePixelRatio||1;if(n(),d(),e.addEventListener("resize",d),e.addEventListener("pageshow",function(e){e.persisted&&d()}),o>=2){var a=t.createElement("body"),s=t.createElement("div");s.style.border=".5px solid transparent",a.appendChild(s),i.appendChild(a),1===s.offsetHeight&&i.classList.add("hairlines"),i.removeChild(a)}}(window,document);`,
                // },
                {
                    innerHTML: `
                     (function flexible (window, document) {
                          var docEl = document.documentElement
                          var dpr = window.devicePixelRatio || 1

                          // adjust body font size
                          function setBodyFontSize () {
                              if (document.body) {
                              document.body.style.fontSize = (12 * dpr) + 'px'
                              }
                              else {
                              document.addEventListener('DOMContentLoaded', setBodyFontSize)
                              }
                          }
                          setBodyFontSize();

                          // set 1rem = viewWidth / 10
                          function setRemUnit () {
                              if (docEl.clientWidth <= 768) {
                                  var rem = docEl.clientWidth / 10
                                  docEl.style.fontSize = rem + 'px'
                              } else {
                                  docEl.style.fontSize = '16px'
                              }
                          }

                          setRemUnit()

                          // reset rem unit on page resize
                          window.addEventListener('resize', setRemUnit)
                          window.addEventListener('pageshow', function (e) {
                              if (e.persisted) {
                              setRemUnit()
                              }
                          })

                          // detect 0.5px supports
                          if (dpr >= 2) {
                              var fakeBody = document.createElement('body')
                              var testElement = document.createElement('div')
                              testElement.style.border = '.5px solid transparent'
                              fakeBody.appendChild(testElement)
                              docEl.appendChild(fakeBody)
                              if (testElement.offsetHeight === 1) {
                              docEl.classList.add('hairlines')
                              }
                              docEl.removeChild(fakeBody)
                          }
                          }(window, document))`,
                },
                // 设置语言和反向布局
                {
                    innerHTML: `const e=(()=>{const e=(()=>{const e=new URL(location.href).searchParams;return Object.fromEntries(e)})();let n="en";const t=(null==e?void 0:e["client-language"])||"en",r=Array.isArray(t)?(null==t?void 0:t[0])||"en":t;return r&&["en","ar","ur","tr","in","zh"].includes(r)&&(n=r),n})();sessionStorage.setItem("lang",e),document.documentElement.lang=e,["ar","ur"].includes(e)&&(document.documentElement.style.direction="rtl");`,
                },
                // {
                //     children: `const baseSize=16;function setRem(){const e=document.documentElement.clientWidth/1920,n=baseSize*Math.min(e,2)>5?baseSize*Math.min(e,2):5;document.documentElement.style.fontSize=n+"px"}setRem(),window.onresize=function(){console.info("onresize..."),setRem()};`,
                // },
            ],
        },
    },

    runtimeConfig: {
        public: {
            apiUrl: process.env.API_URL,
            baseUrl: process.env.NUXT_APP_BASE_URL,
            env: process.env.ENV,
            cdnUrl: process.env.NUXT_APP_CDN_URL,
            i18n: {
                baseUrl: 'https://example.com',
                // smothing other options ...
            },
        },
    },

    // 只自动生成pages一级目录下的.vue文件的路由
    hooks: {
        'pages:extend'(pages: any[]) {
            function removePagesMatching(pattern: RegExp, pages: any[] = []) {
                const pagesToRemove = [];
                for (const page of pages) {
                    if (pattern.test(page.file)) {
                        pagesToRemove.push(page);
                    } else {
                        removePagesMatching(pattern, page.children);
                    }
                }
                for (const page of pagesToRemove) {
                    pages.splice(pages.indexOf(page), 1);
                }
            }
            removePagesMatching(
                /\/Component\/|\/component\/|\/Components\/|\/Component\/|(.ts)$|(.js)$/,
                pages
            );
        },
        'build:manifest'(manifest: any) {
            for (const key in manifest) {
                const file = manifest[key];
                // 禁用图片Prefetch
                if (file.assets) {
                    file.assets = file.assets.filter(
                        (asset: string) =>
                            !asset.endsWith('.webp') &&
                            !asset.endsWith('.jpg') &&
                            !asset.endsWith('.png') &&
                            !asset.endsWith('.jpeg') &&
                            !asset.endsWith('.svg')
                    );
                }
                // 禁用其他页面的prefetch
                file.dynamicImports = [];
            }
        },
    },

    gtag: {
        id: 'G-R7C72ZVQC8',
    },
    // postcss: {
    //     plugins: {
    //         'postcss-pxtorem': {
    //             rootValue: 75,
    //             propList: ['*'],
    //             selectorBlackList: ['van-', 'xgplayer', ':root', 'van_', '--van', /^body$/],
    //         },
    //     },
    // },
    // module.exports = {
    //     plugins: {
    //         'autoprefixer': {
    //             overrideBrowserslist: [
    //                 '> 0.5%',
    //                 'last 2 versions',
    //                 'ie > 11',
    //                 'iOS >= 10',
    //                 'Android >= 5',
    //             ],
    //         },
    //         /* 设置样式时 px 自动转换为 rem */
    //         'postcss-pxtorem': {
    //             rootValue: 37.5,
    //             propList: ['*'],
    //             exclude: /(node_modules|bootstrap)/i,
    //         },
    //     },
    // };

    // postcss: {
    //     plugins: {
    //         'postcss-pxtorem': {
    //             rootValue: 75,
    //             propList: ['*'],
    //             selectorBlackList: ['van-', 'xgplayer', ':root', 'van_', '--van', /^body$/],
    //         },
    //     },
    // },
    postcss: {
        plugins: {
            'postcss-pxtorem': {
                rootValue: 37.5, // 换算的基数 vant的是37.5, 设计稿375
                // rootValue: 16,
                selectorBlackList: [], // 忽略转换正则匹配项 列入一些ui库, ['.el'] 就是忽略elementUI库
                propList: ['*'],
                exclude: /(node_modules|bootstrap)/i,
            },
        },
    },
    vite: {
        server: {
            proxy: {
                '/api': {
                    target: 'https://192.168.11.157',
                    changeOrigin: true,
                    rewrite: path => path.replace(/^\/api/, ''),
                },
            },
        },
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: '@use "@/global.scss" as *;',
                },
            },
        },
        // iOS 16.0 兼容性修复
        build: {
            target: ['es2015', 'safari16'], // 支持 iOS 16.0
            rollupOptions: {
                output: {
                    // 修复模块解析问题
                    manualChunks: undefined,
                    // 确保模块正确解析
                    format: 'es'
                }
            }
        },
        // 修复模块解析
        resolve: {
            alias: {
                '#entry': '/.nuxt/entry.mjs'
            }
        }
    },

    devtools: {
        enabled: true,
    },

    compatibilityDate: '2024-11-26',
    
    // iOS 16.0 兼容性配置
    ssr: false,
    
    // 修复 iOS 16.0 的模块解析问题
    build: {
        transpile: ['#entry']
    },
});
